package com.tokenplus.thai.home

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.tokenplus.thai.R
import com.tokenplus.thai.adata.user.ReqGetUserWallet
import com.tokenplus.thai.aviewmodel.CheckinViewModel
import com.tokenplus.thai.aviewmodel.CoinsViewModel
import com.tokenplus.thai.aviewmodel.ConfigViewModel
import com.tokenplus.thai.aviewmodel.UserViewModel
import com.tokenplus.thai.base.BaseActivity
import com.tokenplus.thai.base.BaseFragment
import com.tokenplus.thai.components.dialog.CheckinRemindDialog
import com.tokenplus.thai.components.dialog.selectAsset.SelectAssetDialog
import com.tokenplus.thai.data.ReqBase
import com.tokenplus.thai.databinding.FragmentHomeBinding
import com.tokenplus.thai.extend.*
import com.tokenplus.thai.home.adapter.HomeAssetsAdapter
import com.tokenplus.thai.home.repo.HomeCoinManager
import com.tokenplus.thai.utils.SpUtil
import java.lang.ref.WeakReference

/** 首页 */
class HomeFragment : BaseFragment() {

    //布局binding
    private lateinit var mFragmentBinding: FragmentHomeBinding

    //适配器
    private lateinit var mHomeAssetsAdapter: HomeAssetsAdapter

    //select asset 弹框
    private lateinit var mBottomSheetDialog: SelectAssetDialog

    //是否点击transfer
    private var mIsToTransfer = false

    //user viewModel
    private val mUserViewModel by lazy {
        ViewModelProvider(this)[UserViewModel::class.java]
    }

    //coins viewModel
    private val mCoinsViewModel by lazy {
        ViewModelProvider(this)[CoinsViewModel::class.java]
    }

    // checkin viewModel
    private val mCheckinViewModel by lazy {
        ViewModelProvider(this)[CheckinViewModel::class.java]
    }

    // checkin viewModel
    private val mConfigViewModel by lazy {
        ViewModelProvider(this)[ConfigViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mUserViewModel)
        list.add(mCoinsViewModel)
        list.add(mCheckinViewModel)
        list.add(mConfigViewModel)
        return list
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mFragmentBinding =
            FragmentHomeBinding.inflate(inflater, container, false)
        return mFragmentBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        try {
            //增加弱牵引
            (requireActivity() as HomeActivity).weakHomeFragment =
                WeakReference(this)

            //初始化刷新组件
            initRefreshUI()

            //初始化select asset dialog
            initSelectAssetDialog()

            //监听返回
            onHandleLiveDataCallback()

            //初始化适配器
            mHomeAssetsAdapter = HomeAssetsAdapter(HomeCoinManager.mAccounts)
            mHomeAssetsAdapter.setItemClickListener { item ->
                val name = item.coinName ?: ""
                val coinType = item.coinType
                val params = HashMap<String, String>()
                params["name"] = name
                params["coinType"] = coinType ?: ""
                (requireActivity() as BaseActivity).startToAssetDetailActivity(params)
            }

            mFragmentBinding.listHomeAssets.layoutManager = LinearLayoutManager(requireActivity())
            mFragmentBinding.listHomeAssets.adapter = mHomeAssetsAdapter

            //点击my wallet
            mFragmentBinding.topNavBarHome.setOnActionClickListener { action ->
                if (action == R.integer.NavbarActionLeft) {
                    (requireActivity() as BaseActivity).startToMyWalletActivity()
                }
            }

            //复制地址
            mFragmentBinding.imageHomeCopy.setOnClickListener {
                HomeCoinManager.mGlobalAddressLiveData.value?.let { address ->
                    requireContext().copyToClipboard(address)
                }
            }

            //点击管理钱包
            mFragmentBinding.imageHomeMore.setOnClickListener {
                //组装参数
//                val coinType = HomeCoinManager.mUserWallet?.coinType ?: ""
                val coinType = HomeCoinManager.mGlobalCoinTypeLiveData.value ?: ""
                val params = HashMap<String, String>()
                params["coinType"] = coinType
                (requireActivity() as BaseActivity).startToManageWalletActivity(params)
            }

            //点击transfer
            mFragmentBinding.llHomeTransfer.setOnClickListener {
                //获取币
                mIsToTransfer = true
                mCoinsViewModel.getCoins(ReqBase(showLoading = false))
            }

            //点击receive
            mFragmentBinding.llHomeReceive.setOnClickListener {
                (requireActivity() as BaseActivity).startToReceiveActivity()
            }

            //点击earn
            mFragmentBinding.llHomeEarn.setOnClickListener {
                (requireActivity() as HomeActivity).toEarnTab()
            }

            // 点击 cash back
            mFragmentBinding.llHomeCashBack.setOnClickListener {
                (requireActivity() as HomeActivity).startToNewComerEnjoyActivity()
            }

            //只有非空时才重新获取
            if (HomeCoinManager.mGlobalCoinTypeLiveData.value == null) {
                //获取币种信息
                mCoinsViewModel.getCoins(ReqBase())
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()

        // 测试
//        val domain = "CHECK_REMIND_TODAY"
//        SpUtil.saveSpValue(domain, "")

        //获取钱包信息
        //getUserWallet(showLoading = false)

        //获取accounts信息
        //getUserAccounts(showLoading = false)

        // 获取红点信息
        getNotifyRedMarkInfo()

        // 获取首充配置
        getFirstRechargeConfig()
    }

    /** 监听live data 返回 */
    @SuppressLint("NotifyDataSetChanged")
    private fun onHandleLiveDataCallback() {
        HomeCoinManager.mGlobalCoinTypeLiveData.observe(viewLifecycleOwner) {
            it?.let {
                //获取钱包信息
                getUserWallet()
            }
        }
        HomeCoinManager.mGlobalMainCoinTypeLiveData.observe(viewLifecycleOwner) {
            it?.let {
                //获取accounts信息
                getUserAccounts()
            }
        }
        HomeCoinManager.mGlobalNameLiveData.observe(viewLifecycleOwner) {
            //更新标题
            mFragmentBinding.topNavBarHome.setCenterText(it)
        }

        mCoinsViewModel.onGetCoinsLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    HomeCoinManager.mCoins.clear()
                    HomeCoinManager.mCoins.addAll(result)

                    if (mIsToTransfer) {
                        mIsToTransfer = false
                        mBottomSheetDialog.updateCurrentTitle(HomeCoinManager.mGlobalNameLiveData.value)
                        mBottomSheetDialog.updateDataList(HomeCoinManager.mCoins)
                        mBottomSheetDialog.show()

                    } else {
                        println("=========================== false")
                        val coin = HomeCoinManager.mCoins.first()
                        //保存全局 address
                        HomeCoinManager.updateGlobalAddress(coin.address)

                        //保存全局 coinType
                        HomeCoinManager.updateGlobalCoinType(coin.coinType)

                        //保存全局 mainCoinType
                        HomeCoinManager.updateGlobalMainCoinType(coin.mainCoinType)

                        //保存全局 name
                        HomeCoinManager.updateGlobalName(coin.name)

                        //保存全局 symbol
                        HomeCoinManager.updateGlobalSymbol(coin.symbol)
                    }
                }
            }
        }

        mUserViewModel.onGetUserWalletLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    //UI更新
                    mFragmentBinding.textHomeWalletName.text = result.name ?: result.coinUnit
                    mFragmentBinding.textHomeWalletAccount.text =
                        result.address.toEllipsisWalletAddress()
                }
            }
        }

        mUserViewModel.onGetUserAccountsResultLiveData.observe(viewLifecycleOwner) { success ->
            stopRefreshState()
            if (success) {
                mHomeAssetsAdapter.notifyDataSetChanged()

                if (HomeCoinManager.mAccounts.size > 0) {
                    mFragmentBinding.emptyLayout.llEmptyList.visibility = View.GONE
                } else {
                    mFragmentBinding.emptyLayout.llEmptyList.visibility = View.VISIBLE
                }
            }
        }

        mCheckinViewModel.onGetRedMarkInfoLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    val showCouponsRedMark = (result.coupons ?: "") == "YES"
                    val showCheckinRedMark = (result.checkIn ?: "") == "YES"
                    val showTabRedMark = (showCheckinRedMark or showCouponsRedMark)
                    (requireActivity() as HomeActivity).makeEarnTabRedMark(showTabRedMark)

                    // 判断是否为当日第1次显示
                    if (showCheckinRedMark) {
                        val showCheckinDialog = mCheckinViewModel.needShowCheckinRemindDialog()
                        if (showCheckinDialog) {
                            val income = result.dayCheckinEarn ?: ""
                            CheckinRemindDialog.showDialog(
                                requireActivity().supportFragmentManager,
                                income
                            ) {
                                mCheckinViewModel.todayDidShowCheckinRemindDialog()
                                mCheckinViewModel.checkin(ReqBase(showLoading = true))
                            }
                        }
                    }
                }
            }
        }

        mCheckinViewModel.onCheckinLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            if (it.isSuccess) {
                Toast.makeText(
                    requireActivity(),
                    getString(R.string.check_in7),
                    Toast.LENGTH_SHORT
                ).show()

                Handler(Looper.getMainLooper()).postDelayed({
                    (requireActivity() as BaseActivity).startToCheckinActivity()
                }, 500)
            }
        }

        mConfigViewModel.onGetFirstRechargeConfigLiveData.observe(viewLifecycleOwner) {
            stopRefreshState()
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    mFragmentBinding.textCashBack.text =
                        getString(R.string.enjoy_5_cash_back, result.toFinancePercentString())
                }
            }
        }
    }

    /** 初始化下拉刷新 */
    private fun initRefreshUI() {
        connectSwipeRefreshLayout(mFragmentBinding.swipeRefresh) {
            //获取钱包
            getUserWallet()
            //获取账号
            getUserAccounts()
        }
    }

    /** 初始化 select asset 弹框 */
    @SuppressLint("NotifyDataSetChanged")
    private fun initSelectAssetDialog() {
        mBottomSheetDialog = SelectAssetDialog(requireActivity())
        mBottomSheetDialog.setItemClickListener { revDataAsset ->
            //组装参数
            val coinType = revDataAsset.coinType ?: ""
            val params = HashMap<String, String>()
            params["coinType"] = coinType
            (requireActivity() as BaseActivity).startToTransferActivity(params)
        }
        mBottomSheetDialog.setItemInputListener { content ->
            mHomeAssetsAdapter.notifyDataSetChanged()
        }
    }

    /** 获取wallet信息 */
    private fun getUserWallet(showLoading: Boolean = false) {
        //获取钱包信息
        HomeCoinManager.mGlobalCoinTypeLiveData.value?.let { coinType ->
            //获取钱包信息
            val reqGetUserWallet = ReqGetUserWallet(coinType = coinType)
            reqGetUserWallet.showLoading = showLoading
            mUserViewModel.getUserWallet(reqGetUserWallet)
        }
    }

    /** 获取accounts信息 */
    private fun getUserAccounts(showLoading: Boolean = false) {
        //获取钱包信息
        HomeCoinManager.mGlobalMainCoinTypeLiveData.value?.let { mainCoinType ->
            //获取钱包信息
            val reqGetUserWallet = ReqGetUserWallet(mainCoinType = mainCoinType)
            reqGetUserWallet.showLoading = showLoading
            mUserViewModel.getUserAccounts(
                viewLifecycleOwner,
                reqGetUserWallet
            )
        }
    }

    /** 获取红点通知信息 */
    private fun getNotifyRedMarkInfo() {
        val reqBase = ReqBase()
        reqBase.showLoading = false
        mCheckinViewModel.getRedMarkInfo(reqBase)
    }

    /** 获取首充配置信息 */
    private fun getFirstRechargeConfig() {
        val reqBase = ReqBase()
        reqBase.showLoading = false
        mConfigViewModel.getFirstRechargeConfig(reqBase)
    }
}